//
//  SettingViewController.swift
//  ifanr
//
//  Created by 😱😱 on 16/9/13.
//  Copyright © 2016年 😱😱. All rights reserved.
//

import UIKit

class SettingViewController: UIViewController {
    // MARK:--------------------------- LifeCycle --------------------------
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
 
    // MARK:---------------------------        UI        --------------------------
    private func setupUI() {
        self.view.backgroundColor = UIColor.blackColor()
        
        let headerView = SettingHeaderView(frame: CGRect(x: 0, y: UIConstant.UI_MARGIN_20, width: self.view.width, height: 44))
        headerView.backBtnDidClick { [unowned self] in
            self.navigationController!.popViewControllerAnimated(true)
            
        }
        self.view.addSubview(headerView)
        
        self.view.addSubview(tableView)
        
        tableView.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(self.view.height-UIConstant.UI_NAV_HEIGHT)
        }
    }
    
    private lazy var tableView: UITableView = {
        let tableView : UITableView = UITableView()
        tableView.backgroundColor = UIColor.blackColor()
        tableView.separatorStyle = .None
        tableView.sectionHeaderHeight = UIConstant.UI_NAV_HEIGHT
        tableView.dataSource  = self
        tableView.delegate    = self
        return tableView
    }()
}

extension SettingViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let model = SettingModelArray[indexPath.row]
        let cell = SetteingTableViewCell(cellType: model.type)
        cell.model = model
        return cell
        
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 50
        }
        return 70
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == 2 {
            self.showTips("清除缓存", duration: 2)
        } else if indexPath.row == 3 {
            self.showTips("评分", duration: 2)
        }
    }
}

//MARK: - 缓存
extension SettingViewController {
    
    func cacheSizeHandle() {
        let calculateFileSize = dispatch_queue_create("Calculate directory size", DISPATCH_QUEUE_CONCURRENT)
        dispatch_async(calculateFileSize, {() -> Void in
            let size: Float = self.folderSizeAtPath(NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).last!)
            dispatch_async(dispatch_get_main_queue(), {() -> Void in
                print(size)
//                SettingModelArray[2].detail = String(format: "已缓存 %.2f M", size/(1024 * 1024))
//                self.tableView.reloadData()
            })
        })
    }
    
    //遍历文件夹获得文件夹大小
    func folderSizeAtPath(filePath: String) -> Float {
        let mFileManager = NSFileManager.defaultManager()
        var totalSize:Float = 0
        //判断字符串是否为文件/文件夹
        var isDir: ObjCBool = ObjCBool(false)
        let exists:Bool = mFileManager.fileExistsAtPath(filePath, isDirectory: &isDir)
        
        if exists {
            if isDir {
                let subFileNames:NSArray = mFileManager.subpathsAtPath(filePath)!
                for subFileName in subFileNames {
                    let subFilePath = (filePath as NSString).stringByAppendingPathComponent(subFileName as! String)
                    totalSize += folderSizeAtPath(subFilePath)
                }
            }else{
                let attr:NSDictionary = try! mFileManager.attributesOfItemAtPath(filePath)
                let size = attr["NSFileSize"] as! Float
                totalSize += size
                
            }
        }else{
            return 0
        }
        return totalSize
    }
    
    //单个文件的大小
    
    func fileSizeAtPath(filePath: String) -> Float {
        let manager = NSFileManager.defaultManager()
        if manager.fileExistsAtPath(filePath) {
            let attr:NSDictionary = try! manager.attributesOfItemAtPath(filePath)
            return attr["NSFileSize"] as! Float
        }
        return 0
    }
    
    //递归删除文件
    func clearFileWithPath(path: String) {
        let fileManager = NSFileManager.defaultManager()
        var isDir: ObjCBool = ObjCBool(false)
        if fileManager.fileExistsAtPath(path, isDirectory: &isDir) {
            if isDir {
                for item: String in fileManager.subpathsAtPath(path)! {
                    self.clearFileWithPath(NSURL(fileURLWithPath: path).URLByAppendingPathComponent(item).absoluteString)
                }
            }
            else {
                do {
                    try fileManager.removeItemAtPath(path)
                }
                catch let error {
                    print("\(error), 删除失败了")
                }
            }
        }
    }
}